import * as echarts from "echarts/core";
import { MapChart } from "echarts/charts";
import { useEffect, useRef } from "react";
import baiyun from "assets/baiyun.json";
import { mapConfig } from "./mapConfig";
import "./index.scss";
export default function Map() {
  const chartRef = useRef(null);
  const timerRef = useRef(null);
  let mapInstance = null;
  let carouselIndex = -1;

  useEffect(() => {
    echarts.registerMap("baiyun", baiyun);
    renderChart();
    mapActive();
    mouseEvents();

    // 清除影响
    return () => {
      // mapInstance && mapInstance.dispose();
      clearInterval(timerRef.current);
    };
  }, []);

  // 初始化echarts
  const renderChart = () => {
    const renderedMapInstance = echarts.getInstanceByDom(chartRef.current);
    if (renderedMapInstance) {
      mapInstance = renderedMapInstance;
    } else {
      mapInstance = echarts.init(chartRef.current);
    }
    echarts.use([MapChart]);
    let data = baiyun.features.map((item) => {
      // 显示窗口的数据转换
      return {
        value: (Math.random() * 1000).toFixed(2),
        name: item.properties.name,
      };
    });
    // 配置地图
    mapInstance.setOption(mapConfig({ setData: data }));
  };

  // 自动轮播高亮效果
  const mapActive = () => {
    const BAIYUN_STREET = baiyun.features.length;
    // 每次进入清空一下定时器
    if (timerRef.current) {
      clearInterval(timerRef.current);
    }
    timerRef.current = setInterval(() => {
      // 取消高亮
      mapInstance.dispatchAction({
        type: "downplay",
        seriesIndex: 0,
      });
      carouselIndex++;

      // 当前下标高亮
      mapInstance.dispatchAction({
        type: "highlight",
        seriesIndex: 0,
        dataIndex: carouselIndex,
      });

      // 展示tooltip
      mapInstance.dispatchAction({
        type: "showTip",
        seriesIndex: 0,
        dataIndex: carouselIndex,
        position: "left",
      });

      if (carouselIndex >= BAIYUN_STREET) {
        carouselIndex = -1;
      }
    }, 4000);
  };

  // 鼠标移入移出
  const mouseEvents = () => {
    mapInstance.on("mouseover", (e) => {
      clearInterval(timerRef.current);
      // 停止定时器，清除之前的显示
      mapInstance.dispatchAction({
        type: "downplay",
        seriesIndex: 0,
        dataIndex: carouselIndex,
      });
    });

    // 鼠标划出定时器开始
    mapInstance.on("mouseout", () => {
      mapActive();
    });
  };

  return (
    <div
      className="map"
      ref={chartRef}
      style={{
        width: "800px",
        height: "800px",
      }}
    ></div>
  );
}
